<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退货单号" prop="prCode">
        <el-input
          v-model="queryParams.prCode"
          placeholder="请输入退货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="prState">
        <el-select v-model="queryParams.prState" placeholder="请选择单据状态" clearable>
          <el-option
            v-if="['0', '1', '4','5','6','8'].includes(dict.value)"
            v-for="dict in dict.type.py_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退货日期" prop="prTime">
        <el-date-picker clearable
          v-model="queryParams.prTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择退货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inrejected:inrejected:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inrejected:inrejected:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inrejected:inrejected:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inrejected:inrejected:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-check"
          size="mini"
          :disabled="single"
          @click="handlecheck"
          v-hasPermi="['inrejected:inrejected:check']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleClose"
          v-hasPermi="['inrejected:inrejected:close']"
        >关闭</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-dialog title="审核" :visible.sync="shopen" width="500px">
      <el-form :model="shform">
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="shform.result">
            <el-radio :label="5">通过</el-radio>
            <el-radio :label="1">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comments">
          <el-input type="textarea" v-model="shform.comments" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="shopen = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table v-loading="loading" :data="inrejectedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left"/>
      <el-table-column label="序号" align="center" prop="" fixed="left" >
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>>
      <el-table-column label="退货单号" align="center" prop="prCode" width="180" fixed="left">
        <template #default="scope">
          <router-link :to="{ path:'/wms/inrejected/inrejected/detail',query:{inrejected:scope.row}}">{{ scope.row.prCode }}</router-link>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="prState" fixed="left">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_status" :value="scope.row.prState"/>
        </template>
      </el-table-column>
      <el-table-column label="退货日期" align="center" prop="prTime" width="180" fixed="left">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.prTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进货单号" align="center" prop="phCode" width="180"/>
      <el-table-column label="供应商" align="center" prop="supplier" width="180"/>
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系方式" align="center" prop="phone" width="180"/>
      <el-table-column label="进货部门" align="center" prop="phDept" />
      <el-table-column label="进货人" align="center" prop="phPerson" />
      <el-table-column label="退货数量" align="center" prop="rejectedNum" />
      <el-table-column label="退货金额" align="center" prop="rejectedMoney" />
      <el-table-column label="进货商品" align="center"  width="280">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.proNames" placement="top">
            <div>{{ changeProNames(scope.row.proNames) }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="所在部门" align="center" prop="createDept" />
      <el-table-column label="制单时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="reviewer" />
      <el-table-column label="审核时间" align="center" prop="reviewerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="['5'].includes(scope.row.prState)"
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleRevoke(scope.row)"
            v-hasPermi="['inrejected:inrejected:revoke']"
          >撤销</el-button>
          <el-button
            v-if="['0', '1'].includes(scope.row.prState)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inrejected:inrejected:edit']"
          >修改</el-button>
          <el-button
            v-if="['0', '1'].includes(scope.row.prState)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inrejected:inrejected:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改进货退货对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退货单号" prop="prCode">
          <el-input v-model="form.prCode" placeholder="请输入退货单号" />
        </el-form-item>
        <el-form-item label="单据状态" prop="prState">
          <el-select v-model="form.prState" placeholder="请选择单据状态">
            <el-option
              v-for="dict in dict.type.py_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退货日期" prop="prTime">
          <el-date-picker clearable
            v-model="form.prTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进货单号" prop="phCode">
          <el-input v-model="form.phCode" placeholder="请输入进货单号" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="进货部门" prop="phDept">
          <el-input v-model="form.phDept" placeholder="请输入进货部门" />
        </el-form-item>
        <el-form-item label="进货人" prop="phPerson">
          <el-input v-model="form.phPerson" placeholder="请输入进货人" />
        </el-form-item>
        <el-form-item label="退货原因" prop="rejectedReason">
          <el-input v-model="form.rejectedReason" placeholder="请输入退货原因" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">${subTable.functionName}信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOdRejectedDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOdRejectedDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="odRejectedDetailsList" :row-class-name="rowOdRejectedDetailsIndex" @selection-change="handleOdRejectedDetailsSelectionChange" ref="odRejectedDetails">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="货品名称" prop="productName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入货品名称" />
            </template>
          </el-table-column>
          <el-table-column label="货品编号" prop="productCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productCode" placeholder="请输入货品编号" />
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="productModel" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productModel" placeholder="请输入规格型号" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="已入库" prop="alreadyNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.alreadyNum" placeholder="请输入已入库" />
            </template>
          </el-table-column>
          <el-table-column label="未入库" prop="notyetNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.notyetNum" placeholder="请输入未入库" />
            </template>
          </el-table-column>
          <el-table-column label="本次退货数量" prop="rejectedNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rejectedNum" placeholder="请输入本次退货数量" />
            </template>
          </el-table-column>
          <el-table-column label="进货单价" prop="inPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inPrice" placeholder="请输入进货单价" />
            </template>
          </el-table-column>
          <el-table-column label="退货金额" prop="rejectedPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rejectedPrice" placeholder="请输入退货金额" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInrejected, getInrejected, delInrejected, addInrejected, updateInrejected,checkbyId,revokebyId,colseById } from "@/api/inrejected/inrejected";

export default {
  name: "Inrejected",
  dicts: ['py_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      se:[],
      // 子表选中数据
      checkedOdRejectedDetails: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 进货退货表格数据
      inrejectedList: [],
      // ${subTable.functionName}表格数据
      odRejectedDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      shopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prCode: null,
        prState: null,
        prTime: null,
        supplier: null,
      },
      // 表单参数
      form: {},
      shform:{
        prId: null
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询进货退货列表 */
    getList() {
      this.loading = true;
      listInrejected(this.queryParams).then(response => {
        this.inrejectedList = response.rows;
        console.log("getList",response.rows)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        prId: null,
        prCode: null,
        prState: null,
        prTime: null,
        phCode: null,
        supplier: null,
        contacts: null,
        phone: null,
        phDept: null,
        phPerson: null,
        rejectedNum: null,
        rejectedMoney: null,
        rejectedReason: null,
        remark: null,
        createBy: null,
        createDept: null,
        createTime: null,
        reviewer: null,
        reviewerReport: null,
        reviewerTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null
      };
      this.odRejectedDetailsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prId)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.se=selection.map(item=>item.prState);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push( {path:'/wms/inrejected/inrejected/add'});
    /*  this.reset();
      this.open = true;
      this.title = "添加进货退货";*/
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prId = row.prId || this.ids
      const prState = row.prState || this.se;
     // (prState)
      if (prState==0 || prState==1 ){
        this.$router.push( {path:'/wms/inrejected/inrejected/update',
          query:{
            id: prId
          }})
      }else {
        this.$modal.msgError("该单据不能修改");
        return;
      }
     /* getInrejected(prId).then(response => {
        this.form = response.data;
        this.odRejectedDetailsList = response.data.odRejectedDetailsList;
        this.open = true;
        this.title = "修改进货退货";
      });*/
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.odRejectedDetailsList = this.odRejectedDetailsList;
          if (this.form.prId != null) {
            updateInrejected(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInrejected(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prIds = row.prId || this.ids;
      if(this.se=='6' ){
        this.$modal.msgError("该单据正在执行，不能删除");
        return;
      }else{
        this.$modal.confirm('是否确认删除进货退货编号为"' + prIds + '"的数据项？').then(function() {
          return delInrejected(prIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
	/** ${subTable.functionName}序号 */
    rowOdRejectedDetailsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddOdRejectedDetails() {
      let obj = {};
      obj.productName = "";
      obj.productCode = "";
      obj.productModel = "";
      obj.unit = "";
      obj.alreadyNum = "";
      obj.notyetNum = "";
      obj.rejectedNum = "";
      obj.inPrice = "";
      obj.rejectedPrice = "";
      obj.remark = "";
      this.odRejectedDetailsList.push(obj);
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteOdRejectedDetails() {
      if (this.checkedOdRejectedDetails.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
      } else {
        const odRejectedDetailsList = this.odRejectedDetailsList;
        const checkedOdRejectedDetails = this.checkedOdRejectedDetails;
        this.odRejectedDetailsList = odRejectedDetailsList.filter(function(item) {
          return checkedOdRejectedDetails.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleOdRejectedDetailsSelectionChange(selection) {
      this.checkedOdRejectedDetails = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inrejected/inrejected/export', {
        ...this.queryParams
      }, `inrejected_${new Date().getTime()}.xlsx`)
    },
    handlecheck(){
      if (this.se!='0'){
        this.$modal.msgError("该单据无需审核");
        return;
      }else {
        this.shopen=true;
      }
    },
    handleSubmit(){
     // alert(this.ids)
      this.shform.prId=this.ids;
      console.log("审核",this.shform);
      checkbyId(this.shform).then(response => {
        this.getList();
        this.shopen=false;
        this.$modal.msgSuccess("已审核");
      })
    },
    handleRevoke(row){
      const  prId=row.prId
     // alert(prId)
      this.$confirm('是否撤回所选单据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        revokebyId(prId).then(respnse=>{
          this.getList();
          this.$message({
            type: 'success',
            message: '撤销成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '撤销删除'
        });
      });
    },
    handleClose(){
      const  prId=this.ids;
     // (prId)
      if (this.se=='6'){
        this.$modal.msgError("该单据无发关闭");
        return;
      }else{
        this.$confirm('是否关闭所选单据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          colseById(prId).then(respnse=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '关闭成功!'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '关闭删除'
          });
        });
      }

    },
    changeProNames(value){
      var arr = [];
      if (typeof value === 'string') {
        arr = value.split(",");
      } else if (Array.isArray(value)) {
        arr = value;
      } else {
        console.error("Invalid type for value:", value);
        arr = [];
      }
      // 如果数组长度小于或等于3，直接连接数组元素
      if (arr.length <= 2) {
        return arr.join('、');
      }
      // 如果数组长度大于3，取前三个元素，然后添加"等X项……"，其中X是数组长度
      var firstThree = arr.slice(0, 2);
      var restCount = arr.length-2;
      return firstThree.join('、') + '等' + restCount + '项……';
    }
  }
};
</script>
